(function(window) {

  var common = {
    iOS: function() {
      return navigator.userAgent.match(/iPhone|iPod/i) ? true : false;
    },
    isAndroid: function() {
      return navigator.userAgent.match(/Android/i) ? true : false;
    },
    isApp: function() {
      return navigator.userAgent.match(/app_sdk/i) ? true : false;
    },
    isIpad: function() {
      return navigator.userAgent.match(/iPad/i) ? true : false;
    },
    isAndroidpad: function() {
      return navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1 && navigator.userAgent.indexOf('pad') > -1;
    },
    isWap: function() {
      return !!navigator.userAgent.match(/AppleWebKit.*Mobile.*/); /*是否为移动终端*/
    },
    getSiteId: function() {
      var siteId = 9;
      if(common.isApp()) {
        if(common.isAndroid()) {
          siteId = 7;
        }
        if(common.isIpad()) {
          siteId = 6;
        }
        if(common.isAndroidpad()) {
          siteId = 7;
        }
        if(common.iOS()) {
          siteId = 3;
        }
      } else {
        if(common.isWap()) {
          siteId = 9;
        } else {
          siteId = 0;
        }
      }
      return siteId;
    },

    /**
     *  开始加载
     * @param msg
     * @param time
     */
    msgShow: function(msg, time) {
      //提示
      layer.open({
        content: msg,
        skin: 'msg',
        time: time || 2 //2秒后自动关闭
      });
    },
    autoLogin:function(cf){
      if(common.isApp()) {
        jsBridge.autoLogin(function(res){
           if(res.errcode==0){
            location.reload();
           }else{
            cf();
           }
        })
      }else{
        cf();
      }
    },
    successTip: function(msg, time) {
      layer.open({
        type: 1,
        shadeClose: false,
        time: time || 2, //2秒后自动关闭,
        shade: false,
        content: '  <div class="message_layer_ show_msg"><i class="success_ico"></i><p class="message_name">' + msg || '操作成功！' + '</p></div>'
      });
    },
    loading: function() {
    if(common.isApp()) {
        jsBridge.hideLoading()
        }
      layer.open({
        type: 1,
        shadeClose: false,
        style: 'border:none; background:none;box-shadow: none;',
        shade: true,
        content: '<img style="width:2rem" src="" />'
      });
    },

    /**
     * 结束加载
     */
    loadingClose: function() {
      layer.closeAll();
    },
     xhr: function(url, data, method, callback) {
      url = url || "";
      data = data || {};
      method = method || "";
      callback = callback || function() {};
      var getKeys = function(obj) {
        var keys = [];
        for(var key in obj) {
          if(obj.hasOwnProperty(key)) {
            keys.push(key)
          }
        }
        return keys
      };
      if(typeof data == "object") {
        var queryString = "";
        var keys = getKeys(data);
        for(var i = 0; i < keys.length; i++) {
          queryString += encodeURIComponent(keys[i]) + "=" + encodeURIComponent(data[keys[i]]);
          if(i != keys.length - 1) {
            queryString += "&"
          }
        }
        url += "" + queryString
      } else {
        if(typeof data == "function") {
          method = data;
          callback = method
        }
      }
      if(typeof method == "function") {
        callback = method;
        method = "callback"
      }
      if(!Date.now) {
        Date.now = function() {
          return new Date().getTime()
        }
      }
      var timestamp = Date.now();
      var generatedFunction = "jsonp" + Math.round(timestamp + Math.random() * 1000001);
      window[generatedFunction] = function(json) {
        callback(json);
        try {
          delete window[generatedFunction]
        } catch(e) {
          window[generatedFunction] = undefined
        }
      };
      if(url.indexOf("?") === -1) {
        url = url + "?"
      } else {
        url = url + "&"
      }
      var jsonpScript = document.createElement("script");
      jsonpScript.setAttribute("src", url + method + "=" + generatedFunction);
      document.getElementsByTagName("head")[0].appendChild(jsonpScript)
    },
    /**
     *  字符串的限制长度
     * @param str
     * @param num
     * @returns {*}
     */
    strLimit: function(str, num) {
      if(str && str.length > num) {
        return str.slice(0, num) + '...';
      } else {
        return str;
      }
    },
    /**
     * 设置sessionStorage数据
     * 格式
     * {key:'',value:''}
     *
     * @param data
     */
    setSessionStorage: function(data) {
      if(typeof(data.value) == 'object') {
        window.sessionStorage.setItem(data.key, JSON.stringify(data.value));
      } else if(typeof(data.value) == 'string') {
        window.sessionStorage.setItem(data.key, data.value);
      }
    },
    /**
     * 设置sessionStorage数据
     * @param key
     * @returns {string}
     */
    getSessionStorage: function(key) {
      var val = window.sessionStorage.getItem(key) || "";
      if(val.search(/:/i) > 0) {
        val = JSON.parse(val);
      }
      return val;
    },
    /**
     * 检测对象是否为空
     * 如果对象为空 true ,反之 相反
     * @param obj
     * @returns {boolean}
     */
    checkObjectNull: function(obj) {
      for(var name in obj) {
        if(obj.hasOwnProperty(name)) {
          return false;
        }
      }
      return true;
    },
    /**
     * 获取url参数
     * 使用方式：getLocationParam.key 这里的key是你参数名
     * @returns {{}}
     */
    getLocationParam: function(p) {
      var url = p ? p : window.location.search;
      var params = url.toString().slice(1).split("&");
      var returnObject = {};
      for(var i = 0; i != params.length; i++) {
        var index = params[i].indexOf("=");
        returnObject[params[i].slice(0, index)] = params[i].slice(index + 1);
      }
      return returnObject;
    },
    /**
     * 格式化 参数
     * @param name
     * @returns {{}}
     */

    getCartKey:function(callback){
      var url = "https://gateway.111.com.cn/shoppingcart/cartkey?tradername=yw_app&trader=h5&closesignature=yes&signature_method=md5&timestamp="+
      new Date().getTime()+"&signature=****&siteid=9"
       common.xhr(url,callback)
    },
    getParam: function(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if(r != null) return unescape(r[2]);
      return null;
    },
    cookie: function(name, value, days) {
      // if value is undefined, get the cookie value
      if(value === undefined) {
        var cookiestring = "; " + window.document.cookie;
        var cookies = cookiestring.split("; " + name + "=");
        if(cookies.length === 2) {
          return cookies.pop().split(";").shift();
        }
        return null;
      } else {
        // if value is a false boolean, we'll treat that as a delete
        if(value === false) {
          days = -1;
        }
        var expires = "";
        if(days) {
          var date = new Date();
          date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
          expires = "; expires=" + date.toGMTString();
        }
        window.document.cookie = name + "=" + value + expires + "; path=/;domain=111.com.cn";
      }
    },
    /**
     * 格式化手机号
     * @param phone
     * @returns {*|XML|void|string}
     */
    formatPhone: function(phone) {
      return phone && phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
    isLogin: function(cf) {
      if(common.isApp()) {
        jsBridge.isLogin({}, function(res) {

          cf(res.data.result);
        })
      } else {
        cf(this.cookie("token") == null ? false : true);
      }

    },
    createUUID: function() {
      var s = [];
      var hexDigits = "ABCDE6709abcdef";
      for(var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    },
    getUUID: function() {
      if(common.isApp()) {
        var ua = navigator.userAgent;
        var ua_ = ua.substring(ua.indexOf("@") - 1);
        if(ua_) {
          return ua_.substring(0, ua_.indexOf("@"))
        } else {
          var uuid = common.createUUID();
          common.cookie("UUID", uuid, 7);
          return uuid;
        }

      } else {
        if(common.cookie("UUID")) {
          return common.cookie("UUID");
        } else {
          var uuid = common.createUUID();
          common.cookie("UUID", uuid, 7);
          return uuid;
        }
      }
    }

  };
  if(typeof define === 'function' && define.amd) {
    // AMD
    define(common);
  } else {
    window.common = common;
  }
})(window)
export default common;
